package com.sneakxy.cloudbase.platform.utils.web.signature;

import java.util.Calendar;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.JWTVerifier;

public class SignatureValidator {

	private Algorithm algorithm;
	
	private JWTVerifier verifier;
	
	/**
	 * 时间相隔多少毫秒内有效
	 */
	private int timeout;
	
	public SignatureValidator(String secretkey) {
		this(secretkey, 5 * 60 * 1000);
	}
	
	public SignatureValidator(String secretkey, int timeout) {
		this.algorithm = Algorithm.HMAC256(secretkey);
		this.timeout = timeout;
		this.verifier = JWT.require(algorithm).build();
	}
	
	public String signature() {
		Calendar now = Calendar.getInstance();
		now.add(Calendar.MILLISECOND, this.getTimeout());
		return JWT.create().withExpiresAt(now.getTime()).sign(algorithm);
	}
	
	public void validate(String signature) throws SignatureTimeoutException, SignatureErrorException {
		try {
			verifier.verify(signature);
		} catch(TokenExpiredException e) {
			throw new SignatureTimeoutException();
		} catch(JWTVerificationException e) {
			throw new SignatureErrorException();
		}
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public Algorithm getAlgorithm() {
		return algorithm;
	}

	public JWTVerifier getVerifier() {
		return verifier;
	}
	
}
